package com.pet.server.ext.util.baidu;

import java.util.LinkedHashMap;

import com.pet.server.ext.Logger;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class DistanceEstimator {

	private static final String URI = "/direction/v1?";
    private static final Logger logger = Logger.getLogger(DistanceEstimator.class);
	public static double route(double srcLat, double srcLon, String srcRegion, double dstLat, double dstLon, String dstRegion){
		logger.logInfo("route(lat="+srcLat+",lon="+srcLon+",srcRegion="+srcRegion+",dstLat="+dstLat+",dstLon="+dstLon+",dstRegion="+dstRegion+")");
		LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
		map.put("origin", srcLat+","+srcLon);
		map.put("origin_region", srcRegion);
		map.put("destination", dstLat+","+dstLon);
		map.put("destination_region", dstRegion);
		map.put("mode", "walking");
		map.put("output", "json");
		double ret = -1;
		try{
	        String retValue = WebClient.io(URI, map);
		    JSONObject json = JSONObject.fromObject(retValue);
		    if (json.containsKey("status") && json.getInt("status") == 0 && json.containsKey("result")) {
		        JSONObject jsonResult = json.getJSONObject("result");
		        if (jsonResult.containsKey("routes")) {
		            JSONArray jsonRoutes = jsonResult.getJSONArray("routes");
		            if (jsonRoutes.size() > 0) {
		                ret = jsonRoutes.getJSONObject(0).getInt("distance") / 1000.0;
		            }
		        }
		    }
		}catch(Exception e){
			e.printStackTrace();
		   logger.logError("route route:"+e.getMessage());
		}
		return ret;
	}
}
